package com.tally.user.controller;

import com.google.code.kaptcha.impl.DefaultKaptcha;
import com.tally.server.config.ConstKey;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * @Author: sy
 * @Date: 2020/12/16 13:31
 * @Description:
 */
@RestController
@RequestMapping("/kaptcha")
public class KaptchaController {
    public static final String BUSINESS_NAME = "图片验证码";
    private static final Logger logger = LoggerFactory.getLogger(KaptchaController.class);
    @Qualifier("getWebKaptcha")
    @Autowired
    private DefaultKaptcha defaultKaptcha;

    @Autowired
    private RedisTemplate redisTemplate;

    @Value("${key.expire-time.imageCode}")
    private Long codeExpireTime;

    @GetMapping("/image-code/{imageCodeToken}")
    public void imageCode(@PathVariable String imageCodeToken, HttpServletRequest request, HttpServletResponse response) throws IOException {
        ByteArrayOutputStream jpegOutputStream = new ByteArrayOutputStream();
        try {
            // 生成验证码字符串
            String createText = defaultKaptcha.createText();
            logger.info("验证码：{}",createText);// 1111
            // 将生成的验证码放入会话缓存中，后续验证的时候用到
//             request.getSession().setAttribute(imageCodeToken, createText);

            redisTemplate.opsForValue().set(imageCodeToken + ConstKey.IMAGE_CODE_SUFFIX,createText,codeExpireTime, TimeUnit.SECONDS);

            // 使用验证码字符串生成验证码图片
            BufferedImage challenge = defaultKaptcha.createImage(createText);
            ImageIO.write(challenge, "jpg", jpegOutputStream);
        } catch (IllegalArgumentException e) {
            response.sendError(HttpServletResponse.SC_NOT_FOUND);
            return;
        }

        // 定义response输出类型为image/jpeg类型，使用response输出流输出图片的byte数组
        byte[] captchaChallengeAsJpeg = jpegOutputStream.toByteArray();
        response.setHeader("Cache-Control", "no-store");
        response.setHeader("Pragma", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        ServletOutputStream responseOutputStream = response.getOutputStream();
        responseOutputStream.write(captchaChallengeAsJpeg);
        responseOutputStream.flush();
        responseOutputStream.close();
    }
}
